package com.tool.toollibrary.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import com.tool.mylibrary.utils.Logger;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Michael on 2017/10/11.
 */

@SuppressLint("AppCompatCustomView")
public class LargeImageView extends ImageView implements View.OnTouchListener {

    private Context mContext;
    public static final String TAG = LargeImageView.class.getSimpleName();
    //区域解码类实例  （我自己这么叫）
    private BitmapRegionDecoder mDecoder;
    /**
     * 图片的宽度和高度
     */
    private int mImageWidth, mImageHeight;

    // 分别记录上次滑动的坐标
    private int mLastX = 0;
    private int mLastY = 0;
    /**
     * 绘制的区域
     */
    private volatile Rect mRect = new Rect();
    private static final BitmapFactory.Options options = new BitmapFactory.Options();

    static {
        options.inPreferredConfig = Bitmap.Config.RGB_565;
    }

    private GestureDetector gestureDetector;

    public LargeImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        Logger.d(TAG, "构造方法执行了");
        init(context);
    }

    private void init(Context context) {
        this.mContext = context;
        super.setOnTouchListener(this);
        super.setClickable(true);
        super.setLongClickable(true);
        super.setFocusable(true);
        super.setScaleType(ScaleType.MATRIX);

        gestureDetector = new GestureDetector(mContext, new MyGestureListener());

    }


    // 以流的方式输入图片源
    public void setInputStream(InputStream is) {

        try {
            mDecoder = BitmapRegionDecoder.newInstance(is, false);
            BitmapFactory.Options tmpOptions = new BitmapFactory.Options();
            tmpOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(is, null, tmpOptions);
            mImageWidth = tmpOptions.outWidth;
            mImageHeight = tmpOptions.outHeight;
            requestLayout();
            invalidate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }


    //将事件传递给 gestureDetector
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {


        gestureDetector.onTouchEvent(motionEvent);

        return true;
    }


    //手势监听类
    class MyGestureListener extends GestureDetector.SimpleOnGestureListener {


        @Override
        public boolean onDown(MotionEvent e) {
            mLastX = (int) e.getRawX();
            mLastY = (int) e.getRawY();
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            super.onLongPress(e);
            mLastX = (int) e.getRawX();
            mLastY = (int) e.getRawY();
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

            Logger.d(TAG, "onScroll方法执行了");

            int x = (int) e2.getRawX();
            int y = (int) e2.getRawY();
            move(x, y);
            return true;

        }

        /**
         * 移动的时候更新图片显示的区域
         *
         * @param x
         * @param y
         */
        private void move(int x, int y) {
            int deltaX = x - mLastX;
            int deltaY = y - mLastY;
            Log.d(TAG, "move, deltaX:" + deltaX + " deltaY:" + deltaY);
            //如果图片宽度大于屏幕宽度
            if (mImageWidth > getWidth()) {
                //移动rect区域
                mRect.offset(-deltaX, 0);

                checkWidth();

                invalidate();
            }
            //如果图片高度大于屏幕高度
            if (mImageHeight > getHeight()) {
                mRect.offset(0, -deltaY);
                checkHeight();
                //重绘
                invalidate();
            }


            mLastX = x;
            mLastY = y;
        }

        //检查宽度
        private void checkWidth() {


            Rect rect = mRect;
            int imageWidth = mImageWidth;
            int imageHeight = mImageHeight;
            //检查是否到达图片最右端
            if (rect.right > imageWidth) {
                rect.right = imageWidth;
                rect.left = imageWidth - getWidth();
            }
            //左端
            if (rect.left < 0) {
                rect.left = 0;
                rect.right = getWidth();
            }
        }

        //检查高度
        private void checkHeight() {

            Rect rect = mRect;
            int imageWidth = mImageWidth;
            int imageHeight = mImageHeight;

            //是否到达底部
            if (rect.bottom > imageHeight) {
                rect.bottom = imageHeight;
                rect.top = imageHeight - getHeight();
            }
            //顶部
            if (rect.top < 0) {
                rect.top = 0;
                rect.bottom = getHeight();
            }
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            int x = (int) e2.getRawX();
            int y = (int) e2.getRawY();
            move(x, y);
            return true;
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            return true;
        }


    }


    @Override
    protected void onDraw(Canvas canvas) {
        Bitmap bm = mDecoder.decodeRegion(mRect, options);
        canvas.drawBitmap(bm, 0, 0, null);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = getMeasuredWidth();
        int height = getMeasuredHeight();

        int imageWidth = mImageWidth;
        int imageHeight = mImageHeight;

        //默认直接显示图片的中心区域，可以自己去调节
        mRect.left = imageWidth / 2 - width / 2;
        mRect.top = imageHeight / 2 - height / 2;
        mRect.right = mRect.left + width;
        mRect.bottom = mRect.top + height;

    }



}
